package com.jsh.config.exception;

import com.google.common.collect.ImmutableMap;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import com.jsh.common.api.response.CommonCode;
import com.jsh.common.api.response.ResponseResult;
import com.jsh.common.api.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Author JiangYaoFeng
 * 2021/5/27 5:14
 */
@ControllerAdvice//控制器增强
public class ExceptionCatch {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    //使用builder来构建一个异常类型和错误代码的异常
    protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();

    //指定捕获的异常类型
    @ExceptionHandler({CustomException.class})
    @ResponseBody
    public ResponseResult customException(CustomException c,ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //update-begin-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
        // 是否允许发送Cookie，默认Cookie不包括在CORS请求之中。设为true时，表示服务器允许Cookie包含在请求中。
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        //update-end-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题

        //记录日志
        LOGGER.error("catch exception:{}", c.getMessage());
        ResultCode resultCode = c.getResultCode();
        return new ResponseResult(resultCode);
    }


    //指定捕获的异常类型
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception e, ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
            httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
            //update-begin-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题
            // 是否允许发送Cookie，默认Cookie不包括在CORS请求之中。设为true时，表示服务器允许Cookie包含在请求中。
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //update-end-author:scott date:20200907 for:issues/I1TAAP 前后端分离，shiro过滤器配置引起的跨域问题

        //记录日志
        LOGGER.error("catch exception:{}", e.getMessage());
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        ResultCode resultCode = EXCEPTIONS.get(e.getClass());
        if (resultCode != null) {
            //已知的异常信息
            return new ResponseResult(resultCode);
        }
        //未知的异常信息
        if(e.getClass()== AuthenticationException.class){


            return new ResponseResult(false,500,e.getMessage());
        }else if(e.getClass()== ServletException.class){
            return new ResponseResult(false,500, e.getCause().getMessage());
        }
        return new ResponseResult(CommonCode.SERVER_ERROR);
    }

    static {
        builder.put(NullPointerException.class, CommonCode.INVALID_PARAM);
        builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
        builder.put(UnauthorizedException.class, CommonCode.UNAUTHORISE);
        builder.put(DataIntegrityViolationException.class,CommonCode.INVALID_PARAM);
        builder.put(MaxUploadSizeExceededException.class, new ResultCode() {
            @Override
            public boolean success() {
                return false;
            }

            @Override
            public int code() {
                return 9999;
            }

            @Override
            public String message() {
                return "文件上传超出限制大小";
            }
        });

    }
}
